﻿using System;
using System.Data;
using System.Security.Cryptography;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;

namespace Stote.Forms
{
    public partial class FrmAreaAddAndEdit : BaseForm
    {
        Form parentForm = null;
        Dong.BLL.StoreArea storeAreaBLL = new Dong.BLL.StoreArea();
        Dong.BLL.Store storeBLL = new Dong.BLL.Store();
        Dong.Model.StoreArea editModel = null;
        int editId = 0;
        public FrmAreaAddAndEdit(int id, Form parent)
        {
            InitializeComponent();
            parentForm = parent;
            Bind();
            btnAdd.Click += BtnAdd_Click;
            btnStore.Click += BtnStore_Click;
            txtTemperature.KeyPress += TxtTemperature_KeyPress;
            txtMinTemperature.KeyPress += TxtMinTemperature_KeyPress;
            txtMaxTemperature.KeyPress += TxtMaxTemperature_KeyPress;

            if (id == 0)
            {
                editId = 0;
                editModel = null;
                WinText = "添加";
                btnAdd.Text = "添加";
                btnAdd.Image = Properties.Resources.add;
                btnStore.Visible = true;
            }
            else
            {
                editId = id;
                editModel = storeAreaBLL.GetModel(editId);
                WinText = "编辑";
                btnAdd.Text = "保存";
                btnAdd.Image = Properties.Resources.save;
                btnStore.Visible = false;

                txtStoreAreaName.Text = editModel.StoreAreaName;
                cbStore.SelectedValue = editModel.StoreId;
                txtTemperature.Text = editModel.Temperature.ToString();
                txtMinTemperature.Text = editModel.MinTemperature.ToString();
                txtMaxTemperature.Text = editModel.MaxTemperature.ToString();
                rtbRemark.Text = editModel.Remark;
            }
        }

        private void BtnStore_Click(object sender, EventArgs e)
        {
            FrmMain mainForm = parentForm.ParentForm as FrmMain;
            mainForm.ToggleSelected("仓库管理");
            mainForm.OpenForm(new FrmStore(), "仓库管理");
            this.Close();
        }

        #region 允许输入数字和小数点

        private void TxtMaxTemperature_KeyPress(object sender, KeyPressEventArgs e)
        {
            System.Windows.Forms.TextBox textBox = sender as System.Windows.Forms.TextBox;
            // 允许输入数字和小数点
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                // 如果输入的不是数字或小数点，则取消输入
                e.Handled = true;
            }
            // 不允许小数点重复出现
            if (textBox.Text.Contains(".") && e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }

        private void TxtMinTemperature_KeyPress(object sender, KeyPressEventArgs e)
        {
            System.Windows.Forms.TextBox textBox = sender as System.Windows.Forms.TextBox;
            // 允许输入数字和小数点
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                // 如果输入的不是数字或小数点，则取消输入
                e.Handled = true;
            }
            // 不允许小数点重复出现
            if (textBox.Text.Contains(".") && e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }

        private void TxtTemperature_KeyPress(object sender, KeyPressEventArgs e)
        {
            System.Windows.Forms.TextBox textBox = sender as System.Windows.Forms.TextBox;
            // 允许输入数字和小数点
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                // 如果输入的不是数字或小数点，则取消输入
                e.Handled = true;
            }
            // 不允许小数点重复出现
            if (textBox.Text.Contains(".") && e.KeyChar == '.')
            {
                e.Handled = true;
            }
        }

        #endregion

        private void Bind()
        {
            DataSet ds = storeBLL.GetList(" Status=0");
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.NewRow();
            dr["StoreId"] = -1;
            dr["StoreName"] = "全部";
            dt.Rows.InsertAt(dr, 0);
            cbStore.DataSource = dt;
            cbStore.DisplayMember = "StoreName";
            cbStore.ValueMember = "StoreId";
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtStoreAreaName.Text.Trim()))
                {
                    MessageBox.Show("请输入区域名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (Convert.ToInt32(cbStore.SelectedValue) == -1)
                {
                    MessageBox.Show("请选择区域所属仓库！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtTemperature.Text.Trim()))
                {
                    MessageBox.Show("请输入温度！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtMinTemperature.Text.Trim()))
                {
                    MessageBox.Show("请输入温度最小值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrEmpty(txtMaxTemperature.Text.Trim()))
                {
                    MessageBox.Show("请输入温度最大值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (Convert.ToDecimal(txtMinTemperature.Text.Trim()) > Convert.ToDecimal(txtMaxTemperature.Text.Trim()))
                {
                    MessageBox.Show("温度最小值不能大于温度最大值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int storeId = Convert.ToInt32(cbStore.SelectedValue);
                if (editId == 0)
                {
                    DataSet ds = storeAreaBLL.GetList($" Status=0 AND StoreAreaName='{txtStoreAreaName.Text.Trim()}'");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        MessageBox.Show($"此区域名称{txtStoreAreaName.Text.Trim()}已存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    int maxNo = 1;
                    DataSet ds2 = storeAreaBLL.GetList($" StoreId={storeId}");
                    int count = ds2.Tables[0].Rows.Count;
                    if (count > 0)
                        maxNo = count + 1;

                    Dong.Model.StoreArea model = new Dong.Model.StoreArea()
                    {
                        StoreAreaNo = $"S-{storeId}-{maxNo.ToString().PadLeft(2, '0')}",
                        StoreAreaName = txtStoreAreaName.Text.Trim(),
                        StoreId = storeId,
                        Temperature = Convert.ToDecimal(txtTemperature.Text.Trim()),
                        MinTemperature = Convert.ToDecimal(txtMinTemperature.Text.Trim()),
                        MaxTemperature = Convert.ToDecimal(txtMaxTemperature.Text.Trim()),
                        Remark = rtbRemark.Text.Trim(),
                        CreateUserId = FrmLogin.CurrentUser.UserId,
                    };

                    storeAreaBLL.Add(model);
                }
                else
                {
                    DataSet ds = storeBLL.GetList($" Status=0 AND StoreName='{txtStoreAreaName.Text.Trim()}' AND StoreId!={editModel.StoreId}");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        MessageBox.Show($"修改后的区域名称{txtStoreAreaName.Text.Trim()}已存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    editModel.StoreAreaName = txtStoreAreaName.Text.Trim();
                    editModel.StoreId = Convert.ToInt32(cbStore.SelectedValue);
                    editModel.Temperature = Convert.ToDecimal(txtTemperature.Text.Trim());
                    editModel.MinTemperature = Convert.ToDecimal(txtMinTemperature.Text.Trim());
                    editModel.MaxTemperature = Convert.ToDecimal(txtMaxTemperature.Text.Trim());
                    editModel.Remark = rtbRemark.Text.Trim();
                    editModel.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                    editModel.LastUpdateTime = DateTime.Now;
                    storeAreaBLL.Update(editModel);
                }


                DataSet ds3 = storeAreaBLL.GetList($" Status=0 AND StoreId={storeId}");
                int rowCount = ds3.Tables[0].Rows.Count;
                if (rowCount > 0)
                {
                    Dong.Model.Store storeModel = storeBLL.GetModel(storeId);
                    storeModel.AreaCount = rowCount;
                    storeModel.LastUpdateUserId = FrmLogin.CurrentUser.UserId;
                    storeModel.LastUpdateTime = DateTime.Now;
                    storeBLL.Update(storeModel);
                }
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }
}
